﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Security.Cryptography;
using System.IO;

namespace FY2013.Business
{
    public class EncryptHelper
    {
        public EncryptHelper()
        {

        }

        public static Guid Md5Encrypt(string text)
        {
            return new Guid(Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(text, "MD5")));
        }

        public static string SHA1Encrypt(string text)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(text, "SHA1");
        }

        public static string ToBase64(string text)
        {
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(text));
        }

        public static string FromBase64(string text)
        {
            return Encoding.UTF8.GetString(Convert.FromBase64CharArray(text.ToArray(), 0, text.Length));
        }

        public static string DESEncrypt(string text)
        {
            byte[] rgbKey = Encoding.UTF8.GetBytes(BusinessSettings.Default.EncryptKey);
            byte[] rgbIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; 
           
            byte[] encryptValue={0};

            byte[] inputByteArray = Encoding.UTF8.GetBytes(text);

            using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    CryptoStream cStream = new CryptoStream(stream, desProvider.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                    stream.Write(inputByteArray, 0, inputByteArray.Length);
                    cStream.FlushFinalBlock();
                    encryptValue = stream.ToArray();
                }
            }
            return Convert.ToBase64String(encryptValue);
        }

        public static string DESDecrypt(string text)
        {
            byte[] rgbKey = Encoding.UTF8.GetBytes(BusinessSettings.Default.EncryptKey);
            byte[] rgbIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

            byte[] inputByteArray = Convert.FromBase64String(text);
            byte[] decryptBuffer = { 0 };

            using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    CryptoStream cStream = new CryptoStream(mStream, desProvider.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                    cStream.Write(inputByteArray, 0, inputByteArray.Length);
                    cStream.FlushFinalBlock();
                    decryptBuffer = mStream.ToArray();
                }
            }
            return Encoding.UTF8.GetString(decryptBuffer);
        }
    }
}
